package cn.marinda.listener;

import cn.marinda.entity.Server;
import cn.marinda.entity.ServerProcess;
import cn.marinda.gui.AbstractHelper;
import cn.marinda.gui.impl.NotFoundServerCoreDialog;
import cn.marinda.util.FileUtils;
import cn.marinda.util.ServerUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * 启动服务器操作事件
 *
 * @author admin
 * @date 2022/07/11
 */
public class StartServerActionEvent implements ActionListener {

    private AbstractHelper helper;
    public StartServerActionEvent(AbstractHelper helper){
        this.helper = helper;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        currentSelectButton();
        if(!FileUtils.findServerCoreExists()){
//            显示没有服务器核心Dialog
            NotFoundServerCoreDialog.instance.close();
            NotFoundServerCoreDialog.instance.open();
            return;
        }else{
            ServerProcess.instance.startServer();
        }

    }



    /**
     * 当前选择按钮
     */
    private void currentSelectButton() {

        for (Component component : helper.getHelperComponentList("ButtonUI")) {
            if (component instanceof JButton) {
                JButton btn = (JButton) component;
                if (btn.getText().equalsIgnoreCase("发送命令")) {
                    continue;
                }
                displayButton();
            }
        }
    }

    /**
     * 显示按钮
     */
    private void displayButton(){
        ServerUtils.openServerFlag = true;
        // 如果开服了
        if(ServerUtils.openServerFlag){
            setButtonEnable("停止服务器",true);
            setButtonEnable("重启服务器",true);
            setButtonEnable("开启服务器",false);
            setButtonEnable("发送命令",true);
            ServerUtils.openServerFlag = false;
        }else{
            setButtonEnable("开启服务器",true);
            setButtonEnable("停止服务器",false);
            setButtonEnable("重启服务器",false);
            setButtonEnable("发送命令",false);
            ServerUtils.openServerFlag = true;
        }
    }


    /**
     * 设置按钮启用
     *
     * @param text 文本
     * @param flag 国旗
     */
    private void setButtonEnable(String text,boolean flag){
        JButton btn = helper.getHelperComponentButtonByText(text);
        btn.setEnabled(flag);
    }

}
